import { reportError } from '../utils/report-error';
import { jwtVerify } from '../utils/jwt';
import validator from 'validator';

/**
 * jwt解析中间件
 * @export
 * @param {*} ctx
 * @param {*} next
 */
export default async function (ctx, next) {
  const token = ctx.header.authorization || '';
  if (token && validator.isJWT(token)) {
    try {
      const tokenInfo = await jwtVerify(token);
      ctx.state.user = tokenInfo;
    } catch (err) {
      // 上报错误
      reportError('JWT解析错误--' + (err as any).toString(), err, {
        priority: '紧急',
        category: '服务器500',
        extra: { url: `${ctx.method} ${ctx.url}`, query: JSON.stringify(ctx.request.query), body: JSON.stringify(ctx.request.body) }
      });
    }
  }
  await next();
}
